﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;

namespace Technullogy.Web.UI.TwcWeather
{
    public static class TwcWeatherManager
    {
        /// <summary>
        /// </summary>
        /// <param name="xmlTwc"></param>
        /// <returns></returns>
        public static weather GetTwcWeather(XmlDocument xmlTwc)
        {
            object objTwc = Deserialize(xmlTwc, typeof(weather));
            return (weather)objTwc;
        }

        /// <summary> 
        /// </summary>
        /// <param name="xmlTwc"></param>
        /// <returns></returns>
        public static search GetTwcSearchResults(XmlDocument xmlTwcSearch)
        {
            object objTwcSearch = Deserialize(xmlTwcSearch, typeof(search));
            return (search)objTwcSearch;
        }

        /// <summary> Deserializes an xml document back into an object
        /// </summary>
        /// <param name="xml">The xml data to deserialize</param>
        /// <param name="type">The type of the object being deserialized</param>
        /// <returns>A deserialized object</returns>
        public static object Deserialize(XmlDocument xml, Type type)
        {
            XmlSerializer s = new XmlSerializer(type);
            string xmlString = xml.OuterXml.ToString();
            byte[] buffer = ASCIIEncoding.UTF8.GetBytes(xmlString);
            MemoryStream ms = new MemoryStream(buffer);
            XmlReader reader = new XmlTextReader(ms);
            Exception caught = null;

            try
            {
                object o = s.Deserialize(reader);
                return o;
            }

            catch (Exception e)
            {
                caught = e;
            }
            finally
            {
                reader.Close();
                ms.Dispose();
                if (caught != null)
                    throw caught;
            }
            return null;
        }
    }
}
